package gofunc

import (
	"bytes"
	"encoding/binary"
	"fmt"
)

type ByteFunc struct {
}

func (self *ByteFunc) Array2HEX(bA []byte) string {
	var str string
	for _, v := range bA {
		s := fmt.Sprintf("%02X ", v)
		str = str + s
	}
	return str
}

func (self *ByteFunc) Array2HEX_noSpace(bA []byte) string {
	var str string
	for _, v := range bA {
		s := fmt.Sprintf("%02X", v)
		str = str + s
	}
	return str
}


//反转一个切片
func (self *ByteFunc)Reverse(a []byte) []byte {
	b:=[]byte{}
	for i := len(a)-1; i >= 0; i-- {
		b=append(b,a[i])
	}
	return b
}

//将byte转换为int16,小端
func (self *ByteFunc) ToInt16LittleEndian(data []byte) (ret int16) {
	buf := bytes.NewBuffer(data)
	binary.Read(buf, binary.LittleEndian, &ret)
	return
}

//将byte转换为int16,大端
func (self *ByteFunc) ToInt16BigEndian(data []byte) (ret int16) {
	buf := bytes.NewBuffer(data)
	binary.Read(buf, binary.BigEndian, &ret)
	return
}

//返回字符在字符串数组的位置，没有找到返回-1
func (self *ByteFunc) IndexOf(arry []byte, value byte) int {
	for k, v := range arry {
		if value == v {
			return k
		}
	}
	return -1
}


// func (self *ByteFunc) ToBCD(i int32) []byte {
// 	var bcd []byte
// 	for i > 0 {
// 		r := i % 10
// 		i /= 10
// 		var x []byte
// 		x = append(x, byte(r))
// 		bcd = append(x, bcd[:]...)
// 	}
// 	return bcd
// }

// 大端bcd 0x001522 > 1522
func (self *ByteFunc) FromBCDBigEndian(bcd []byte) int32 {
	// 代表个十百千
	position := int32(1)
	re := int32(0)
	for i := len(bcd) - 1; i >= 0; i-- {
		b := bcd[i]
		bb := b & 0x0f
		re = re + int32(bb)*position
		position = position * 10
		bb1 := (b >> 4) & 0x0f
		re = re + int32(bb1)*position
		position = position * 10
	}
	return re
}

// 小端bcd 0x001522 > 22150000
func (self *ByteFunc) FromBCDLittleEndian(bcd []byte) int32 {
	// 代表个十百千
	position := int32(1)
	re := int32(0)
	for i := 0; i < len(bcd); i++ {
		b := bcd[i]
		bb := b & 0x0f
		re = re + int32(bb)*position
		position = position * 10
		bb1 := (b >> 4) & 0x0f
		re = re + int32(bb1)*position
		position = position * 10
	}
	return re
}